package com.summer.framework.common.config.feign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.summer.framework.common.entity.FeignError;
import com.summer.framework.common.exception.BaseException;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import java.io.IOException;

/**
 * @auther: 杨杰
 * @date: 2019/5/16 16:10
 * @description:
 */
@Slf4j
public class UserErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = null;
        try {
            // 获取原始的返回内容
            String json = Util.toString(response.body().asReader());
            log.info("decode  json:" + json);
            log.info("response.status():" + response.status());
            JSONObject userJson = JSONObject.parseObject(json);
            FeignError result = JSON.toJavaObject(userJson, FeignError.class);
            log.info("===result  result:" + result);
            exception = new BaseException(result.getStatus(), result.getMessage());

            //new WebApplicationException(javax.ws.rs.core.Response.status(response.status()).entity(result).type(MediaType.APPLICATION_JSON).build());//JSON.toJavaObject(userJson, BaseException.class);
            //new WebApplicationException(javax.ws.rs.core.Response.status(response.status()).entity(result).type(MediaType.APPLICATION_JSON).build());
            log.error("=======exception=======", exception.getMessage());
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
        /*if (400 <= response.status() || response.status() < 500){
            exception = new HystrixBadRequestException("request exception wrapper", exception);
        }else{
            log.error("===else====",exception.getMessage(), exception);
        }*/
        //return FeignException.errorStatus(methodKey, response);
        return exception;
    }
}
